package com.sky.controller.admin;

import com.sky.dataTransmit.DishDTO;
import com.sky.dataTransmit.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.view.DishVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@Slf4j
@Api("菜品接口")
@RestController("adminDishController")
@RequestMapping("/admin/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public Result insert(@RequestBody DishDTO dishDTO){
        log.info("新增菜品 {}",dishDTO);
        clearRedis("category_" + dishDTO.getCategoryId());
        dishService.insert(dishDTO);
        clearRedis("category_" + dishDTO.getCategoryId());
        return Result.success("新增菜品");
    }

    @GetMapping("/page")
    public Result<PageResult> getList(DishPageQueryDTO dishPageQueryDTO){
        log.info("分页查询菜品 {}",dishPageQueryDTO);
        PageResult pageResult= dishService.getList(dishPageQueryDTO);
        return Result.success("分页查询菜品",pageResult);
    }

    @DeleteMapping
    public Result delete(@RequestParam List<Long> ids){
        log.info("删除菜品 {}",ids);
        clearRedis("category_*");
        dishService.delete(ids);
        clearRedis("category_*");
        return Result.success("删除菜品");
    }

    @GetMapping("/{id}")
    public Result<DishVO> getById(@PathVariable Long id){
        log.info("根据id查询菜品 {}",id);
        DishVO dishVO=dishService.getById(id);
        return Result.success("根据id查询菜品",dishVO);
    }

    @PutMapping
    public Result update(@RequestBody DishDTO dishDTO){
        log.info("修改菜品 {}",dishDTO);
        clearRedis("category_*");
        dishService.update(dishDTO);
        clearRedis("category_*");
        return Result.success("修改菜品");
    }

    @PostMapping("/status/{status}")
    public Result updateStatus(@PathVariable Integer status,Long id){
        log.info("菜品售卖状态修改 {} {}",status,id);
        clearRedis("category_*");
        dishService.updateStatus(status,id);
        clearRedis("category_*");
        return Result.success("菜品售卖状态修改");
    }

    @GetMapping("/list")
    public Result<List<Dish>> getByCategoryId(Long categoryId){
        log.info("根据分类查询菜品 {}",categoryId);
        List<Dish> dishes=dishService.getByCategoryId(categoryId);
        return Result.success("根据分类查询菜品",dishes);
    }

    //清理缓存
    private void clearRedis(String key) {
        log.info("清理缓存 {}",key);
        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);
    }
}
